package com.bestcem.xm.survey.service.reportHandler.type;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.survey.service.reportHandler.BaseReportHandler;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Component
public class MatrixSingleScoreHandler implements BaseReportHandler {

    @Override
    public Double getMaxScore(JSONObject question, JSONArray scoreRule) {
        if (question == null || question.getJSONArray("items") == null) {
            return 0d;
        }
        JSONArray items = Optional.ofNullable(question.getJSONArray("items")).orElse(new JSONArray());
        JSONArray rowItems = Optional.ofNullable(question.getJSONArray("rows_items")).orElse(new JSONArray());
        JSONObject scoreGidDict = getMatrixScoreGidDict(scoreRule);

        double maxScore = 0d;

        for (int i = 0; i < rowItems.size(); i++) {
            List<Double> scoreList = new ArrayList<>();
            JSONObject rows = rowItems.getJSONObject(i);
            for (int j = 0; j < items.size(); j++) {
                JSONObject item = items.getJSONObject(j);
                Double score = Optional.ofNullable(scoreGidDict.getDouble(rows.getString("gid") + "_" + item.getString("gid"))).orElse(0d);
                scoreList.add(score);
            }
            if (CollectionUtils.isNotEmpty(scoreList)) {
                maxScore += Collections.max(scoreList);
            }
        }
        return convertFloat(maxScore);
    }

    @Override
    public Double getScore(JSONObject question, Object answers, JSONArray scoreRule, JSONObject scoreConfig) {
        double score = 0.0;
        JSONObject scoreGidDict = getMatrixScoreGidDict(scoreRule);
        JSONObject answersJs = (JSONObject)answers;
        if (answersJs == null || answersJs.isEmpty()) {
            return convertFloat(score);
        }
        List<String> keys = new ArrayList<>(answersJs.keySet());
        for (int i = 0; i < keys.size(); i++) {
            String row = keys.get(i);
            JSONArray item = answersJs.getJSONArray(row);
            if (item != null && !item.isEmpty()) {
                score += Optional.ofNullable(scoreGidDict.getDouble(row + "_" + item.getString(0))).orElse(0d);
            }
        }
        return convertFloat(score);
    }

    @Override
    public List<String> getQuestionTypeValue() {
        return Collections.singletonList("matrix_single");
    }
}
